package com.voice.server.command;

import java.util.concurrent.*;

public class CycleAckExecute {

    private static int[] sleepTimes=new int[]{0,10,30,60,120,180,240,300,360,420,480,540,600};

    private ScheduledThreadPoolExecutor scheduledThreadPoolExecutor;

    public CycleAckExecute(ScheduledThreadPoolExecutor scheduledThreadPoolExecutor){
        this.scheduledThreadPoolExecutor=scheduledThreadPoolExecutor;
    }

    public void execute(int cycleTimes,Callable<Boolean> callable){
        TimesCallable timesCallable=new TimesCallable(0,cycleTimes,callable,scheduledThreadPoolExecutor);
        timesCallable.run();
    }

    class TimesCallable implements Runnable{

        private int times;
        private int maxTimes;
        private Callable<Boolean> callable;
        private ScheduledThreadPoolExecutor scheduled;

        public TimesCallable(int times,int maxTimes, Callable<Boolean> callable,ScheduledThreadPoolExecutor scheduled) {
            this.times = times;
            this.maxTimes=maxTimes;
            this.callable = callable;
            this.scheduled=scheduled;
        }

        @Override
        public void run() {
            if(times>maxTimes) return;
            times++;
            CompletableFuture.supplyAsync(()-> {
                try {
                    return callable.call();
                } catch (Exception e) {
                    return false;
                }
            }).thenAccept(result->{
                if(!result) scheduled.schedule(this,sleepTimes[times],TimeUnit.SECONDS);
            });
        }
    }
}
